/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package memory;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.Timer;
import javax.swing.UIManager;

/**
 *
 * @author DAM110
 */
public final class VentanaPrincipal extends javax.swing.JFrame implements ActionListener{

    Gestora g = new Gestora();
    Tema tema;
    Dificultad d;
    ConectarCliente c;
    Timer temp;

    public Gestora getG() {
        return g;
    }
    
    
    public VentanaPrincipal() {
        
        
        JPanel a = new PanelImagen("/imagenes/background.jpg");
        this.setContentPane(a);
        iniciarConexion();
        
        initComponents();
        this.setLocationRelativeTo(null);
        g.recuperarNombresObject();
        cbNombres.setModel(new DefaultComboBoxModel(g.devuelveNombresUsados()));
        pDificultad.setLayout(new java.awt.GridLayout(Dificultad.values().length, 1));
        pTema.setLayout(new java.awt.GridLayout(Tema.values().length, 1));
        this.generarPaneles();
        
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT
     * modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bgTema = new javax.swing.ButtonGroup();
        bgDifi = new javax.swing.ButtonGroup();
        pTema = new javax.swing.JPanel();
        pDificultad = new javax.swing.JPanel();
        bRank = new javax.swing.JButton();
        bJugar = new javax.swing.JButton();
        cbNombres = new javax.swing.JComboBox();
        bGuardar = new javax.swing.JButton();
        bCrear = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        pTema.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.SoftBevelBorder(0), "TEMAS", 0, 0, null, java.awt.Color.white));
        pTema.setForeground(new java.awt.Color(255, 255, 255));
        pTema.setLayout(new java.awt.GridLayout(1, 1));

        pDificultad.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.SoftBevelBorder(0), "DIFICULTAD", 0, 0, null, java.awt.Color.white));
        pDificultad.setForeground(new java.awt.Color(255, 255, 255));
        pDificultad.setLayout(new java.awt.GridLayout(1, 1));

        bRank.setBackground(new java.awt.Color(0, 0, 0));
        bRank.setText("RANKING");
        bRank.setBorderPainted(false);
        bRank.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRankActionPerformed(evt);
            }
        });

        bJugar.setBackground(new java.awt.Color(0, 0, 0));
        bJugar.setText("JUGAR");
        bJugar.setBorderPainted(false);
        bJugar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bJugarActionPerformed(evt);
            }
        });

        bGuardar.setBackground(new java.awt.Color(0, 0, 0));
        bGuardar.setText("Guardar Partidas");
        bGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGuardarActionPerformed(evt);
            }
        });

        bCrear.setBackground(new java.awt.Color(0, 0, 0));
        bCrear.setText("Crear Jugador");
        bCrear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCrearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cbNombres, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(346, 346, 346)
                                .addComponent(bRank)
                                .addGap(50, 50, 50))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(bJugar)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(pTema, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(47, 47, 47)
                        .addComponent(bGuardar)
                        .addGap(18, 18, 18)
                        .addComponent(bCrear, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 76, Short.MAX_VALUE)
                        .addComponent(pDificultad, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bRank)
                    .addComponent(cbNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(bJugar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 226, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(pDificultad, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
                            .addComponent(pTema, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(bGuardar)
                            .addComponent(bCrear))
                        .addGap(28, 28, 28))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bJugarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bJugarActionPerformed
        
        if(this.comprobarSeleccion()){
            
            temp.restart();
            this.empezar();
        }
    }//GEN-LAST:event_bJugarActionPerformed

    private void bRankActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRankActionPerformed
        
        new VentanaRanking(this,true).setVisible(true);
    }//GEN-LAST:event_bRankActionPerformed

    private void bGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGuardarActionPerformed
        
        g.guardarExternoChooser();
    }//GEN-LAST:event_bGuardarActionPerformed

    private void bCrearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCrearActionPerformed
        
        String jugador = JOptionPane.showInputDialog("Introduce tu nombre:");
        g.crearJugador(jugador);
        cbNombres.setModel(new DefaultComboBoxModel(g.devuelveNombresUsados()));
        cbNombres.setSelectedItem(jugador);
    }//GEN-LAST:event_bCrearActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaPrincipal().setVisible(true);
            }
        });
    }
    
    private void generarPaneles(){
        
        this.pTema.setOpaque(false);
        
        for(String s:Tema.getTemas()){
            
            JRadioButton a = new JRadioButton(s);
            a.addActionListener(this);
            a.setForeground(Color.WHITE);
            a.setOpaque(false);
            bgTema.add(a);
            this.pTema.add(a); 
        }
        
        
        this.pDificultad.setOpaque(false);
       
        for(String s:Dificultad.nombres()){
            
            JRadioButton a = new JRadioButton(s);
            a.addActionListener(this);
            a.setForeground(Color.WHITE);
            a.setOpaque(false);
            bgDifi.add(a);
            this.pDificultad.add(a);
        }
    }
    
    private boolean comprobarSeleccion(){
        
        boolean devolver = true;
        if(bgDifi.getSelection() == null){
            JOptionPane.showMessageDialog(this, "No has seleccionado Dificultad");
            devolver = false;
        }
        if(bgTema.getSelection() == null){
            JOptionPane.showMessageDialog(this, "No has seleccionado Tema");
            devolver = false;
        }
        return devolver;
    }
    
    private void empezar(){
        
        String jugador;
        if(cbNombres.getSelectedIndex() == -1){
            
            jugador = JOptionPane.showInputDialog("Introduce tu nombre:");
            g.crearJugador(jugador);
            cbNombres.setModel(new DefaultComboBoxModel(g.devuelveNombresUsados()));
        }else{
            
            jugador = (String) cbNombres.getSelectedItem();
        }
        
        g.setJugador(new Jugador(jugador));
        g.iniciarPartida(tema,d);
        new VentanaJuego(this,true).setVisible(true);
    }
    
    public void iniciarConexion(){
        
        ActionListener al = new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                new ConectarCliente(g.getPuntuacion()).start();
            }          
        };
        temp = new Timer(120000,al);   
        temp.start();        
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCrear;
    private javax.swing.JButton bGuardar;
    private javax.swing.JButton bJugar;
    private javax.swing.JButton bRank;
    private javax.swing.ButtonGroup bgDifi;
    private javax.swing.ButtonGroup bgTema;
    private javax.swing.JComboBox cbNombres;
    private javax.swing.JPanel pDificultad;
    private javax.swing.JPanel pTema;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent e) {
        
        JRadioButton fuente = (JRadioButton)e.getSource();
        if(Tema.devuelveTema(fuente.getText()) != null){
            
            tema = Tema.devuelveTema(fuente.getText());
        }else if(Dificultad.devuelveDificultad(fuente.getText()) != null){
            
            d = Dificultad.devuelveDificultad(fuente.getText());
        }
    }
}
